import QQMapWX from "./qqmap-wx-jssdk.min.js";

import {
  baseURL,
  config,
  timeout,
  wxMapkey
} from "../config.js";
import moment from "./moment.js";
import {
  getProvincecode
} from "../api/api.js";
/* 提示 */
export let Toast = (title, icon, time) => {
  uni.showToast({
    title,
    icon: icon || "none",
    mask: true,
    duration: time || 2000,
  });
};

export function errorToast(message) {
  setTimeout(() => {
    Toast(message);
  }, 500)
}

/* 路由跳转 */
export function handleClickRouter(e) {
  let token = wx.getStorageSync("X-MINI-TOKEN");
  if (!token) {
    whetherLogin();
    return;
  }

  let user = uni.getStorageSync("user");
  if (!user.realNameAuthentication) {
    // realNameAuthentication    是否实名认证   0：未认证     1：已认证
    onlyChangeComplete(); // TODO 放开注释
    return;
  }
  let url = e.currentTarget.dataset.url;
  let type = e.currentTarget.dataset.type;

  if (url.includes("警务服务")) {
    Toast("暂未开发");
    return;
  }
  if (type == "tabBar") {
    uni.switchTab({
      url,
    });
  } else {
    uni.navigateTo({
      url,
    });
  }
}

// 判断当前用户是否登录
export const whetherLogin = () => {
  let token = uni.getStorageSync("X-MINI-TOKEN");
  if (!token) {
    uni.showModal({
      title: "提示",
      content: "请先登录",
      success: function(res) {
        if (res.confirm) {
          wx.redirectTo({
            url: "/pages/beforeLogin/beforeLogin",
          });
          return;
        } else if (res.cancel) {
          return false;
        }
      },
    });
  }
};

//判断当前用户是否完善信息
const onlyChangeComplete = () => {
  wx.navigateTo({
    url: "/pages/realNameAuthentication/realNameAuthentication",
  });
  return;
};

// 判断当前图片是否404
export function checkImg(imgurl) {
  return new Promise(function(resolve, reject) {
    wx.getImageInfo({
      src: imgurl,
      success(res) {
        resolve(res);
      },
      fail(err) {
        reject(err);
      },
    });
  });
}

//提示弹窗
export function popup(confirm, content, cancel, showCancel = true) {
  wx.showModal({
    title: "提示",
    content: content || "是否删除？",
    showCancel: showCancel,
    success(res) {
      if (res.confirm) {
        if (confirm && confirm instanceof Function) {
          confirm();
        } else {
          hint("CallBack is no a function");
        }
      } else if (res.cancel) {
        if (cancel) {
          cancel();
        }
      }
    },
  });
}

// 返回上一页  或  指定页面
export let navBack = (url, delta = 1, time = 1000) => {
  if (!url || url == "back") {
    return uni.navigateBack({
      delta: delta,
    });
  }

  uni.reLaunch({
    url,
  });
};

/* 根据条件查找对象 */
export function findItem(arr, params, value) {
  let obj = {};
  if (!(arr instanceof Array)) {
    return;
  }
  obj = arr.find((item) => {
    return item[params] == value;
  });
  return obj;
}

// 预览图片
export function pvwImage(url) {
  if (url) {
    return uni.previewImage({
      urls: url,
      success: (res) => {},
    });
  }
  return;
}

/* 时间格式化 */
export function formatters(timestamp, type) {
  var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
  var YY = date.getFullYear();
  var MM =
    date.getMonth() + 1 < 10 ?
    "0" + (date.getMonth() + 1) :
    date.getMonth() + 1;
  var DD = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
  var HH = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
  var mm = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
  var ss = date.getSeconds();
  let time;
  time = YY + "-" + MM + "-" + DD + " " + HH + ":" + mm + ":00";
  if (type == "YY") {
    time = YY;
  }
  if (type == "MM") {
    time = MM;
  }
  if (type == "DD") {
    time = DD;
  }
  if (type == "HH") {
    time = HH;
  }
  if (type == "mm") {
    time = mm;
  }
  if (type == "ss") {
    time = ss;
  }
  if (type == "YY-MM") {
    time = YY + "-" + MM;
  }
  if (type == "YY-MM-DD") {
    time = YY + "-" + MM + "-" + DD;
  }
  if (type == "YY/MM/DD") {
    time = YY + "/" + MM + "/" + DD;
  }
  if (type == "YY-MM-DD HH") {
    time = YY + "-" + MM + "-" + DD + " " + HH;
  }
  if (type == "YY-MM-DD HH:mm") {
    time = YY + "-" + MM + "-" + DD + " " + HH + ":" + mm;
  }
  if (type == "YY/MM/DD HH:mm") {
    time = YY + "/" + MM + "/" + DD + " " + HH + ":" + mm;
  }
  if (type == "YY/MM/DD HH:mm:ss") {
    time = YY + "/" + MM + "/" + DD + " " + HH + ":" + mm + ":" + ss;
  }
  if (type == "YY-MM-DD HH:mm:ss") {
    time = YY + "-" + MM + "-" + DD + " " + HH + ":" + mm + ":" + ss;
  }
  if (type == "timestamp") {
    time = date.getTime();
  }
  if (type == "wordMinute") {
    time = YY + "年" + MM + "月" + DD + "日" + HH + "时" + mm + "分";
  }
  if (type == "wordMinuteJian") {
    time = YY + "年" + MM + "月" + DD + "日" + HH + ":" + mm;
  }
  if (type == "wordTime") {
    time = YY + "年" + MM + "月" + DD + "日" + HH + "时";
  }
  if (type == "wordDay") {
    time = YY + "年" + MM + "月" + DD + "日";
  }
  return time;
}

/* 时间格式化 中文*/
export function formattersWord(dateStr) {
  let yymmdd = formatters(dateStr, "YY-MM-DD");

  var dict = {
    0: "零",
    1: "一",
    2: "二",
    3: "三",
    4: "四",
    5: "五",
    6: "六",
    7: "七",
    8: "八",
    9: "九",
    10: "十",
    11: "十一",
    12: "十二",
    13: "十三",
    14: "十四",
    15: "十五",
    16: "十六",
    17: "十七",
    18: "十八",
    19: "十九",
    20: "二十",
    21: "二十一",
    22: "二十二",
    23: "二十三",
    24: "二十四",
    25: "二十五",
    26: "二十六",
    27: "二十七",
    28: "二十八",
    29: "二十九",
    30: "三十",
    31: "三十一",
  };
  var date = yymmdd.split("-"),
    yy = date[0],
    mm = +date[1],
    dd = +date[2];

  var yearStr = dict[yy[0]] + dict[yy[1]] + dict[yy[2]] + dict[yy[3]] + "年",
    monthStr = dict["" + Number(mm)] + "月",
    dayStr = dict[dd] + "日";

  return yearStr + monthStr + dayStr;
}

// 日期转时间戳
export function dayTurnTime(time) {
  var date = new Date(time);
  return date.getTime();
}

/* 筛掉无用得字段 */
export function fitterItem(obj) {
  let params = {};
  if (obj instanceof Object) {
    for (let key in obj) {
      if (obj[key] && obj[key] != "undefined") {
        params[key] = obj[key];
      } else {
        continue;
      }
    }
  }
  return params;
}
/**
 * @param {Object} data上传文件
 */
export function uploadFile(data) {
  // let promise = new Promise((resolve, reject) => {
  //   uni.uploadFile({
  //     url: baseURL + data.url,
  //     ...data,
  //     header: getHeader(),
  //     success(res) {
  //       resolve(res);
  //     },
  //     fail(error) {
  //       reject(error);
  //     },
  //   });
  // });
  // return promise;
  return uni.$u.http.upload(data.url, {
    ...data,
  });
}

/**
 *  FormData格式传参
 * @param url  上传路径
 * @param name  上传标识名字
 * @param file  文件内容
 * @param data  其他数据
 */
export function uploadFormdata(url, name, file, data = {}) {
  return new Promise((resolve, reject) => {
    let token = uni.getStorageSync("X-MINI-TOKEN");
    wx.request({
      url: baseURL + url,
      method: "POST",
      header: {
        "X-MINI-TOKEN": token,
        "content-type": "application/x-www-form-urlencoded",
      },
      data: json2Form(data),
      success: function(res) {
        console.log(res, "rrrrrrrrrrr");
      },
      fail: function(res) {
        console.log(res, "错误的");
      },
    });
  });
}

export function json2Form(json) {
  var str = [];
  for (var p in json) {
    str.push(encodeURIComponent(p) + "=" + encodeURIComponent(json[p]));
  }
  return str.join("&");
}


const validateIdent = {
  aIdentityCode_City: { // 城市代码列表  
    11: "北京",
    12: "天津",
    13: "河北",
    14: "山西",
    15: "内蒙古",
    21: "辽宁",
    22: "吉林",
    23: "黑龙江 ",
    31: "上海",
    32: "江苏",
    33: "浙江",
    34: "安徽",
    35: "福建",
    36: "江西",
    37: "山东",
    41: "河南",
    42: "湖北 ",
    43: "湖南",
    44: "广东",
    45: "广西",
    46: "海南",
    50: "重庆",
    51: "四川",
    52: "贵州",
    53: "云南",
    54: "西藏 ",
    61: "陕西",
    62: "甘肃",
    63: "青海",
    64: "宁夏",
    65: "新疆",
    71: "台湾",
    81: "香港",
    82: "澳门",
    91: "国外 "
  },
  IdentityCode_isCardNo(card) { //检查号码是否符合规范，包括长度，类型  
    var reg = /(^\d{15}$)|(^\d{17}(\d|X)$)/; //身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X  
    if (reg.test(card) === false) {
      return false;
    }
    return true;
  },
  IdentityCode_checkProvince(card) { //取身份证前两位，校验省份    
    var province = card.substr(0, 2);
    if (validateIdent.aIdentityCode_City[province] == undefined) {
      return false;
    }
    return true;
  },
  IdentityCode_checkBirthday(card) { //检查生日是否正确，15位以'19'年份来进行补齐。  
    var len = card.length;
    //身份证15位时，次序为省（3位）市（3位）年（2位）月（2位）日（2位）校验位（3位），皆为数字    
    if (len == '15') {
      var re_fifteen = /^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$/;
      var arr_data = card.match(re_fifteen); // 正则取号码内所含出年月日数据  
      var year = arr_data[2];
      var month = arr_data[3];
      var day = arr_data[4];
      var birthday = new Date('19' + year + '/' + month + '/' + day);
      return validateIdent.IdentityCode_verifyBirthday('19' + year, month, day, birthday);
    }
    //身份证18位时，次序为省（3位）市（3位）年（4位）月（2位）日（2位）校验位（4位），校验位末尾可能为X    
    if (len == '18') {
      var re_eighteen = /^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/;
      var arr_data = card.match(re_eighteen); // 正则取号码内所含出年月日数据  
      var year = arr_data[2];
      var month = arr_data[3];
      var day = arr_data[4];
      var birthday = new Date(year + '/' + month + '/' + day);
      return validateIdent.IdentityCode_verifyBirthday(year, month, day, birthday);
    }
    return false;
  },
  IdentityCode_verifyBirthday(year, month, day, birthday) { //校验日期 ，15位以'19'年份来进行补齐。
    var now = new Date();
    var now_year = now.getFullYear();
    //年月日是否合理    
    if (birthday.getFullYear() == year &&
      (birthday.getMonth() + 1) == month &&
      birthday.getDate() == day) {
      //判断年份的范围（3岁到150岁之间)    
      var time = now_year - year;
      if (time >= 0 && time <= 150) {
        return true;
      }
      return false;
    }
    return false;
  },
  IdentityCode_checkParity(card) { //校验位的检测  
    card = validateIdent.IdentityCode_changeFivteenToEighteen(card); // 15位转18位    
    var len = card.length;
    if (len == '18') {
      var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
      var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
      var cardTemp = 0,
        i, valnum;
      for (i = 0; i < 17; i++) {
        cardTemp += card.substr(i, 1) * arrInt[i];
      }
      valnum = arrCh[cardTemp % 11];
      if (valnum == card.substr(17, 1)) {
        return true;
      }
      return false;
    }
    return false;
  },
  IdentityCode_changeFivteenToEighteen(card) { //15位转18位身份证号   
    if (card.length == '15') {
      var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
      var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
      var cardTemp = 0,
        i;
      card = card.substr(0, 6) + '19' + card.substr(6, card.length - 6);
      for (i = 0; i < 17; i++) {
        cardTemp += card.substr(i, 1) * arrInt[i];
      }
      card += arrCh[cardTemp % 11];
      return card;
    }
    return card;
  },
  IdentityCodeValid(card) { //   身份证号码检验主入口 
    let pass = true;
    let sex = ''
    //是否为空    
    if (pass && card === '')
      pass = false;
    //校验长度，类型    
    if (pass && validateIdent.IdentityCode_isCardNo(card) === false)
      pass = false;
    //检查省份    
    if (pass && validateIdent.IdentityCode_checkProvince(card) === false)
      pass = false;
    //校验生日    
    if (pass && validateIdent.IdentityCode_checkBirthday(card) === false)
      pass = false;
    //检验位的检测    
    if (pass && validateIdent.IdentityCode_checkParity(card) === false)
      pass = false;
    if (pass) {
      var iCard = validateIdent.IdentityCode_changeFivteenToEighteen(card);
      if (parseInt(iCard.charAt(16)) % 2 == 0) {
        sex = "0"; // 女生  
      } else {
        sex = "1"; // 男生  
      }
      return true
    } else {
      return false
    }
  }
}


//身份证校验
export function checkIDCard(idCard) {
  return validateIdent.IdentityCodeValid(idCard)
}

//通过身份证号计算年龄、性别、出生日期
export function idCardParse(userCard, num) {
  //获取出生日期
  var birth;
  if (num == 1) {
    birth =
      userCard.substring(6, 10) +
      "-" +
      userCard.substring(10, 12) +
      "-" +
      userCard.substring(12, 14);
    return birth;
  }
  //获取性别
  if (num == 2) {
    if (parseInt(userCard.substr(16, 1)) % 2 == 1) {
      return "男";
    } else {
      return "女";
    }
  }
  //获取年龄
  if (num == 3) {
    var myDate = new Date();
    var month = myDate.getMonth() + 1;
    var day = myDate.getDate();
    var age = myDate.getFullYear() - userCard.substring(6, 10) - 1;
    if (
      userCard.substring(10, 12) < month ||
      (userCard.substring(10, 12) == month && userCard.substring(12, 14) <= day)
    ) {
      age++;
    }
    return age;
  }
}

//*号隐藏信息
export function hiddenInfo(str, frontLen = 3, endLen = 4) {
  console.log("str", str);
  var len = str.length - frontLen - endLen;
  var start = "";
  for (var i = 0; i < len; i++) {
    start += "*";
  }
  return (
    str.substring(0, frontLen) + start + str.substring(str.length - endLen)
  );
}

// 图片转为base64
export function getBase64(img) {
  return new Promise((resolve, reject) => {
    wx.downloadFile({
      url: img,
      success(res) {
        wx.getFileSystemManager().readFile({
          filePath: res.tempFilePath, //选择图片返回的相对路径
          encoding: "base64", //编码格式
          success: (res) => {
            resolve("data:image/png;base64," + res.data);
          },
        });
      },
    });
  });
}

// 图片转为base64  第二种方式
export function getBase64Two(img) {
  return new Promise((resolve, reject) => {
    uni.getFileSystemManager().readFile({
      filePath: img, //选择图片返回的相对路径
      encoding: "base64", //编码格式
      success: (res) => {
        resolve("data:image/png;base64," + res.data);
      },
      fail: (e) => {
        console.log("图片转换失败");
      },
    });
  });
}

// 新版本微信小程序二维码生成函数
export function drawMyQrcode(argument) {
  let obj = null;
  if (argument.type == "String") {
    obj = argument.id;
  }

  if (argument.type == "Object") {
    obj = argument;
    delete obj.type;
  }
  // 加密的message;
  let message = JSON.stringify(obj);
  //秘钥key
  var key = "5kxi7J1zqHBAxAiwQ2GJwnVUH8JoFrqn";
  var base64 = CryptoJS.enc.Utf8.parse(key);

  //加密
  function encrypt() {
    var text = message;
    var encrypt = CryptoJS.TripleDES.encrypt(text, base64, {
      iv: CryptoJS.enc.Utf8.parse("01234567"), //iv偏移量
      mode: CryptoJS.mode.ECB, //ECB模式
      padding: CryptoJS.pad.Pkcs7, //padding处理
    });
    return encrypt.toString(); //加密完成后，转换成字符串
  }

  // 加密
  // let tex = encrypt()

  let tex;
  let text;
  if (argument.type == "String") {
    text = message.substring(1, message.length - 1);
  } else {
    // 不加密
    tex = message;
    text = "&" + tex + "#";
  }

  console.log("新加密结果为：", text);
  var imgData = QR.drawImg(text, {
    typeNumber: 4,
    errorCorrectLevel: "H",
    size: 500,
  });
  return imgData;
}

// 逾期/倒计时  算出天数
export function getNumberDays(day) {
  let timeStamp = dayTurnTime(day);
  let currentStamp = Date.now();

  if (timeStamp > currentStamp) {
    // 倒计时
    let num_day = Math.ceil((timeStamp - currentStamp) / (1000 * 60 * 60 * 24));
    return [true, num_day];
  } else if (timeStamp < currentStamp) {
    // 逾期
    let num_day = Math.ceil((currentStamp - timeStamp) / (1000 * 60 * 60 * 24));
    return [false, num_day];
  }
}

// 去除空格
export function uniTrim(value, spec = "both") {
  return uni.$u.trim(value);
}

// 统一信用代码校验
export function checkSocialCardNumber(value = "") {
  if (value == "") {
    return true;
  } else {
    var firstarray = [
      "0",
      "1",
      "2",
      "3",
      "4",
      "5",
      "6",
      "7",
      "8",
      "9",
      "A",
      "B",
      "C",
      "D",
      "E",
      "F",
      "G",
      "H",
      "I",
      "J",
      "K",
      "L",
      "M",
      "N",
      "O",
      "P",
      "Q",
      "R",
      "S",
      "T",
      "U",
      "V",
      "W",
      "X",
      "Y",
      "Z",
    ];
    var firstkeys = [3, 7, 9, 10, 5, 8, 4, 2];
    var secondarray = [
      "0",
      "1",
      "2",
      "3",
      "4",
      "5",
      "6",
      "7",
      "8",
      "9",
      "A",
      "B",
      "C",
      "D",
      "E",
      "F",
      "G",
      "H",
      "J",
      "K",
      "L",
      "M",
      "N",
      "P",
      "Q",
      "R",
      "T",
      "U",
      "W",
      "X",
      "Y",
    ];
    var secondkeys = [
      1, 3, 9, 27, 19, 26, 16, 17, 20, 29, 25, 13, 8, 24, 10, 30, 28,
    ];

    function calc(code, array1, array2, b) {
      var count = 0;
      for (var i = 0; i < array2.length; i++) {
        var a = code[i];
        count += array2[i] * array1.indexOf(a);
      }
      var remainder = count % b;
      return remainder === 0 ? 0 : b - remainder;
    }
    var code = value.toUpperCase();
    if (code.length != 18) {
      console.log(1);
      return false;
    }
    var reg = /^\w\w\d{6}\w{9}\w$/;
    if (!reg.test(code)) {
      console.log(2);
      return false;
    } else {
      /*
            登记管理部门代码：使用阿拉伯数字或大写英文字母表示。​
            机构编制：1​
            民政：5​
            工商：9​
            其他：Y
        */
      let reg1 = /^[1,5,9,Y]\w\d{6}\w{9}\w$/;
      if (!reg1.test(code)) {
        console.log(3);
        return false;
      } else {
        /*
            机构类别代码：使用阿拉伯数字或大写英文字母表示。​
            机构编制机关：11打头​​
            机构编制事业单位：12打头​
            机构编制中央编办直接管理机构编制的群众团体：13打头​​
            机构编制其他：19打头​
            民政社会团体：51打头​
            民政民办非企业单位：52打头​
            民政基金会：53打头​
            村民委员会：54打头
            民政其他：59打头​
            工商企业：91打头​
            工商个体工商户：92打头​
            工商农民专业合作社：93打头​
            其他：Y1打头​
            https://www.hftfund.com/contents/2019/10/10-3c400690bdb34720a22ad68e22956601.html
        */
        let reg2 =
          /^(11|12|13|19|21|31|32|33|34|35|41|51|52|53|54|55|61|62|59|71|72|81|91|92|93|A1|G1|J1|N1|N2|N3|Y1)\d{6}\w{9}\w$/;
        if (!reg2.test(code)) {
          console.log(4);
          return false;
        } else {
          /*
                登记管理机关行政区划码：只能使用阿拉伯数字表示。按照GB/T 2260编码。​
                例如：四川省成都市本级就是510100；四川省自贡市自流井区就是510302。​
                */
          let reg3 =
            /^(11|12|13|19|21|31|32|33|34|35|41|51|52|53|54|55|61|62|59|71|72|81|91|92|93|A1|G1|J1|N1|N2|N3|Y1)\d{6}\w{9}\w$/;
          if (!reg3.test(code)) {
            console.log(5);
            return false;
          } else {
            var firstkey = calc(code.substr(8), firstarray, firstkeys, 11);
            var firstword;
            if (firstkey < 10) {
              firstword = firstkey;
            }
            if (firstkey == 10) {
              firstword = "X";
            } else if (firstkey == 11) {
              firstword = "0";
            }
            if (firstword != code.substr(16, 1)) {
              console.log(6);
              return false;
            } else {
              var secondkey = calc(code, secondarray, secondkeys, 31);
              var secondword = secondarray[secondkey];
              if (!secondword || secondword != code.substr(17, 1)) {
                console.log(7);
                return false;
              } else {
                var word = code.substr(0, 16) + firstword + secondword;
                if (code != word) {
                  console.log(8);
                  return false;
                } else {
                  console.log(9);
                  return true;
                }
              }
            }
          }
        }
      }
    }
  }
}

// 医疗机构登记号校验
export function medicalTreatment(value = "") {
  if (value == "") {
    return true;
  } else if (value.length != 22) {
    return false;
  } else {
    // 组织机构9位
    var num = value.substr(0, 9);
    var patrnSpecial = /^PDY[0-9]{5}[0-9A-Z]{1}$/.test(num); // 验证组织机构

    // 机构属性代码13位    行政区划分代码6位 +  经济类代码2位 + 卫生机构（组织）类别代码4位 + 机构分类管理代码1位
    // 行政区划分代码
    if (patrnSpecial) {
      var area = value.substr(9, 2); // 省
      var city = value.substr(11, 2); // 市
      var district = value.substr(13, 2); // 区

      // 省验证
      // var areaFlag =
      //   /^[11]|[12]|[13]|[14]|[15]|[21]|[22]|[23]|[31]|[32]|[33]|[34]|[35]|[36]|[37]|[41]|[42]|[43]|[44]|[45]|[46]|[50]|[51]|[52]|[53]|[54]|[61]|[62]|[63]|[64]|[65]|[71]|[81]|[82]|[91]$/.test(
      //     area
      //   );
      var areaList = [
        "11",
        "12",
        "13",
        "14",
        "15",
        "21",
        "22",
        "23",
        "31",
        "32",
        "33",
        "34",
        "35",
        "36",
        "37",
        "41",
        "42",
        "43",
        "44",
        "45",
        "46",
        "50",
        "51",
        "52",
        "53",
        "54",
        "61",
        "62",
        "63",
        "64",
        "65",
        "71",
        "81",
        "82",
        "91",
      ];
      var areaFlag = areaList.indexOf(area) == "-1" ? false : true;

      // 市验证     01--70
      var cityFlag = /^7[0]$|^[0-6]\d$|^[0-9]$/.test(city);
      // 区验证     01--99
      var districtFlag = /^9[9]$|^[0-9]\d$|^[0-9]$/.test(district);

      // 经济类代码
      if (areaFlag && cityFlag && districtFlag) {
        var economic = value.substr(15, 2);
        // var economicFlag =
        //   /^[11]|[12]|[13]|[14]|[15]|[16]|[17]|[19]|[20]|[31]|[22]|[23]|[24]|[29]|[30]|[31]|[32]|[33]|[34]|[39]|[90]$/.test(
        //     economic
        //   );

        var economicList = [
          "11",
          "12",
          "13",
          "14",
          "15",
          "16",
          "17",
          "19",
          "20",
          "31",
          "22",
          "23",
          "24",
          "29",
          "30",
          "31",
          "32",
          "33",
          "34",
          "39",
          "90",
        ];
        var economicFlag =
          economicList.indexOf(economic) == "-1" ? false : true;

        if (economicFlag) {
          // 卫生机构（组织）类别代码
          var tissue = value.substr(17, 2);
          // var tissueFlag =
          //   /^[A1]|[A2]|[A3]|[A5]|[A6]|[A7]|[B1]|[B2]|[C1]|[C2]|[D1]|[D2]|[D3]|[D4]|[D5]|[D6]|[E1]|[E2]|[E3]|[F1]|[F2]|[G1]|[G2]|[G3]|[G4]|[H1]|[H2]|[J1]|[J2]|[J3]|[J4]|[K1]|[L1]|[L2]|[L3]|[L4]|[L5]|[L6]|[L9]|[M1]|[M2]|[M3]|[M4]|[M5]|[M6]|[M7]|[N1]|[N2]|[N3]|[O1]|[O2]|[P1]|[P2]|[P9]|[Q1]|[Q2]|[Q3]|[Q9]$/.test(
          //     tissue
          //   );
          var tissueList = [
            "A1",
            "A2",
            "A3",
            "A5",
            "A6",
            "A7",
            "B1",
            "B2",
            "C1",
            "C2",
            "D1",
            "D2",
            "D3",
            "D4",
            "D5",
            "D6",
            "E1",
            "E2",
            "E3",
            "F1",
            "F2",
            "G1",
            "G2",
            "G3",
            "G4",
            "H1",
            "H2",
            "J1",
            "J2",
            "J3",
            "J4",
            "K1",
            "L1",
            "L2",
            "L3",
            "L4",
            "L5",
            "L6",
            "L9",
            "M1",
            "M2",
            "M3",
            "M4",
            "M5",
            "M6",
            "M7",
            "N1",
            "N2",
            "N3",
            "O1",
            "O2",
            "P1",
            "P2",
            "P9",
            "Q1",
            "Q2",
            "Q3",
            "Q9",
          ];
          var tissueFlag = tissueList.indexOf(tissue) == "-1" ? false : true;

          if (tissueFlag) {
            // 机构分类管理代码;
            var institution = value.substr(21, 1);
            var institutionFlag = /^[1]|[2]|[9]$/.test(institution);

            if (institutionFlag) {
              return true;
            } else {
              return false;
            }
          } else {
            return false;
          }
        } else {
          return false;
        }
      } else {
        return false;
      }
    } else {
      return false;
    }
  }
}

// 15位统一社会信用代码(旧)正则校验
export function registerNumber(value = "") {
  if (value == "") {
    return true;
  } else {
    var reg = /^[0-9]{15}$/;
    if (!reg.test(value)) {
      return false;
    } else {
      return true;
    }
  }
}

// 正整数
export function isNumber(s) {
  return /^[1-9]\d*$/.test(s);
}

// 正整数 + 0  （正的整数）
export function positiveNumber(s) {
  return /^\d+$/.test(s);
}

// 只能输入数字，可输入到小数点后两位
export function isNumberTwo(s) {
  return /^(\d+\.?)?\d{0,2}$/.test(s);
}

// 手机号校验
// let reg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
export function regPhone(s) {
  return /^1[23456789]\d{9}$/.test(s)
}

// 判断字段是否为 undefined
export function ifUndefined(s) {
  return typeof s == "undefined";
}

// 判断字段是否为 null       true是为null
export function isNull(s) {
  // console.log(!s && typeof s != "undefined"); // true
  return !s && typeof s != "undefined";
}

export function isNull2(value) {
  return value === null;
}

// 判断字段是否为数字
export function isNum(s) {
  return typeof s === "number" && !isNaN(s);
}

// -防抖
export function debounce(fn, wait) {
  let delay = wait || 2000;
  let timer;
  return function() {
    let args = arguments;
    if (timer) {
      clearTimeout(timer);
      console.log("拦截");
    }
    let callNow = !timer;
    timer = setTimeout(() => {
      timer = null;
    }, delay);
    if (callNow) fn.apply(this, args);
  };
}

// 加载提示
export function isLoading(flag = true) {
  if (flag) {
    uni.showLoading({
      title: "加载中...",
      mask: true,
    });
  } else {
    uni.hideLoading({
      noConflict: true
    });
  }
}

// 判断是否有网络
export function useNetWork() {
  let networkStatusListener = null;

  function checkNetStatus() {
    getNetStatus()
      .then((res) => {
        console.log("有网", res);
        // 如果已有监听器，则移除
        if (networkStatusListener) {
          uni.offNetworkStatusChange(networkStatusListener);
          networkStatusListener = null;
        }
      })
      .catch((err) => {
        console.error("检查网络状态失败", err);
        setTimeout(() => {
          uni.showToast({
            title: "网络不太顺畅，请检查网络设置",
            icon: "none",
            mask: true,
            duration: 2000,
          });
        }, 100);

        // 添加网络状态变化监听器
        networkStatusListener = uni.onNetworkStatusChange(function(res) {
          if (res.isConnected) {
            uni.showToast({
              title: "网络已恢复",
              icon: "none",
              mask: true,
              duration: 2000,
            });
            // 移除监听器，避免重复添加
            uni.offNetworkStatusChange(networkStatusListener);
            networkStatusListener = null;
          }
        });
      });
  }

  // 初始检查网络状态
  checkNetStatus();
}

function getNetStatus() {
  return new Promise((resolve, reject) => {
    uni.getNetworkType({
      success(res) {
        if (res.networkType === "none") {
          reject();
        } else {
          resolve();
        }
      },
    });
  });
}

// 1~31日选择
export function daySele() {
  let dayNum = [{
      text: "1",
      value: 1,
    },
    {
      text: "2",
      value: 2,
    },
    {
      text: "3",
      value: 3,
    },
    {
      text: "4",
      value: 4,
    },
    {
      text: "5",
      value: 5,
    },
    {
      text: "6",
      value: 6,
    },
    {
      text: "7",
      value: 7,
    },
    {
      text: "8",
      value: 8,
    },
    {
      text: "9",
      value: 9,
    },
    {
      text: "10",
      value: 10,
    },
    {
      text: "11",
      value: 11,
    },
    {
      text: "12",
      value: 12,
    },
    {
      text: "13",
      value: 13,
    },
    {
      text: "14",
      value: 14,
    },
    {
      text: "15",
      value: 15,
    },
    {
      text: "16",
      value: 16,
    },
    {
      text: "17",
      value: 17,
    },
    {
      text: "18",
      value: 18,
    },
    {
      text: "19",
      value: 19,
    },
    {
      text: "20",
      value: 20,
    },
    {
      text: "21",
      value: 21,
    },
    {
      text: "22",
      value: 22,
    },
    {
      text: "23",
      value: 23,
    },
    {
      text: "24",
      value: 24,
    },
    {
      text: "25",
      value: 25,
    },
    {
      text: "26",
      value: 26,
    },
    {
      text: "27",
      value: 27,
    },
    {
      text: "28",
      value: 28,
    },
    {
      text: "29",
      value: 29,
    },
    {
      text: "30",
      value: 30,
    },
    {
      text: "31",
      value: 31,
    },
  ];
  return dayNum;
}

/**
 * 多叉树寻找路径
 */
export function findPath(list, targetValue, keyName, path = []) {
  for (let i = 0; i < list.length; i++) {
    const item = list[i];
    path.push(item);
    if (item[keyName] === targetValue) {
      return path;
    }
    if (item.children && item.children.length > 0) {
      const foundPath = findPath(item.children, targetValue, keyName, [
        ...path,
      ]);
      if (foundPath) {
        return foundPath;
      }
    }
    path.pop();
  }
  return null;
}

/** 获取路由传递参数
 * @param {Object} options
 * @param {Object} name
 */
export function getOptionsParams(options, name = "params") {
  if (name) {
    try {
      return JSON.parse(decodeURIComponent(options[name]));
    } catch (error) {
      console.log(error)
      //TODO handle the exception
    }
  }
  try {
    return JSON.parse(decodeURIComponent(options));
  } catch (error) {
    console.log(error)
    //TODO handle the exception
  }
  return {}
}

/**
 * @param {Object} value车牌号验证
 */
export function checkCarNumber(value) {
  return /^(([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z](([0-9]{5}[DF])|([DF]([A-HJ-NP-Z0-9])[0-9]{4})))|([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳使领]))$/
    .test(
      value
    );
}

// 假设base64Data是你的base64字符串，extension是图片的扩展名，如'.png'或'.jpg'

/**
 * 将 base64 转换成 微信的临时文件
 */
export function base64ToImage(base64Data, extension = ".png") {
  const fs = uni.getFileSystemManager();
  const filePath = `${uni.env.USER_DATA_PATH}/temp_image${extension}`; // 图片保存路径
  const base64 = base64Data.split(",")[1]; // 获取base64字符串部分
  return new Promise((resolve, reject) => {
    fs.writeFile({
      filePath: filePath,
      data: base64,
      encoding: "base64",
      success: (res) => {
        // 成功保存图片后的操作，比如显示图片等
        resolve(filePath);
      },
      fail: (err) => {
        reject(err);
      },
    });
  });
}

/**
 * @param {Object} func 将普通函数变成 promise 的形式
 */
export function promisic(func) {
  return function(params = {}) {
    let p = new Promise((resolve, reject) => {
      const args = Object.assign(params, {
        success(res) {
          resolve(res);
        },
        fail(err) {
          reject(err);
        },
      });
      func(args);
    });
    return p;
  };
}

/**
 * @param {Object} params获取经纬度
 */
export function getLocation(params = {}) {
  return new Promise((resolve, reject) => {
    uni.getLocation({
      type: "gcj02",
      success: function(res) {
        resolve(res);
      },
      fail(err) {
        setTimeout(() => {
          errorToast('请在小程序设置中开启允许使用位置信息！')
        }, 300)
        reject(err);
      },
    });
  })
}

/**
 * @param {Object} rootNodes  要查找的数组
 * @param {Object} targetValue 要查找的目标值
 * @param {Object} originKey 查找到源数组中的 key
 */
export function findValueInTree(rootNodes, targetValue, originKey) {
  // 递归辅助函数
  function traverse(nodes) {
    for (let node of nodes) {
      if (node[originKey] === targetValue) {
        return node; // 如果找到目标值，返回true
      }
      if (node.children && node.children.length > 0) {
        // 如果有子节点，则递归搜索子节点
        let foundNode = traverse(node.children);
        if (foundNode) {
          return foundNode; // 如果在任何子节点中找到目标值，返回true
        }
      }
    }
    return null; // 如果没有找到目标值，返回 null
  }

  // 从根节点数组开始遍历
  return traverse(rootNodes);
}

/**
 * @param {Object} day获取几天之前的时间戳
 */
export function getTimestampDaysAgo(day) {
  // 获取当前时间
  var now = new Date();

  // 计算5天前的日期
  var fiveDaysAgo = new Date(now.getTime() - 5 * 24 * 60 * 60 * 1000);

  // 转换为时间戳
  var timestamp = fiveDaysAgo.getTime();

  return timestamp;
}

/**
 * 获取当天最晚的时间戳
 */
export function getEndOfTodayTimestamp() {
  // 创建一个Date对象，默认为当前日期和时间
  var now = new Date();

  // 将时间设置为当天的最后一刻
  now.setHours(23, 59, 59, 999);

  // 获取这个时间的时间戳
  var timestamp = now.getTime();

  return timestamp;
}

/**
 * 获取当天的时间戳
 */
export function getCurrentTimestamp() {
  // 创建一个Date对象，默认为当前日期和时间
  var now = new Date();

  // 获取这个时间的时间戳（毫秒）
  var timestamp = now.getTime();

  return timestamp;
}

export function getHeader(extraParams = {}) {
  let header = {
    "Content-Type": "application/json", // 默认值
  };
  Object.assign(header, extraParams);
  console.log(header);
  let token = uni.getStorageSync("X-MINI-TOKEN");
  let role = config.role;
  if (token) {
    const requestTokenName = config.roleConfig[role].requestTokenName;
    header[requestTokenName] = token;
  }
  return header;
}

export function selectNation(dictMapping, nation) {
  // 民族，默认选中
  let nationText = `${nation}族`;
  let nationOption = dictMapping["nation"].find(
    (item) => item.text === nationText
  );
  return nationOption;
}

export function roundToTwoDecimalPlaces(num) {
  if (num) {
    return num.toFixed(2);
  }
  return 0;
}

/**
 * @param {Object} e页面跳转
 */
export function navigatorTo(e) {
  let url = e.currentTarget.dataset.url; // 路径
  let type = e.currentTarget.dataset.type; // 跳转类型
  let params = e.currentTarget.dataset.params; // 跳转参数

  url = params ?
    url + "?params=" + encodeURIComponent(JSON.stringify(params)) :
    url;

  if (type == "tabBar") {
    uni.switchTab({
      url,
    });
  } else {
    uni.navigateTo({
      url,
    });
  }
}

/**
 * 获取当前位置经纬度
 */
export async function getposition() {
  const location = await getLocationInfo();
  return location;
}

export function getLocationInfo() {
  return new Promise((resolve, reject) => {
    let location = {
      longitude: 0,
      latitude: 0,
      province: "",
      city: "",
      area: "",
      street: "",
      address: "",
      formatted_addresses: "",
    };
    // 使用uni.getLocation获取经纬度
    uni.getLocation({
      type: "gcj02",
      isHighAccuracy: true,
      success(res) {
        location.longitude = res.longitude;
        location.latitude = res.latitude;
        // 创建实例
        const qqmapsdk = new QQMapWX({
          key: wxMapkey,
        });
        // 使用腾讯的逆地址解析
        qqmapsdk.reverseGeocoder({
          location,
          // sig,
          success(response) {
            let info = response.result;
            location.province = info.address_component.province;
            location.city = info.address_component.city;
            location.area = info.address_component.district;
            location.street = info.address_component.street;
            location.address = info.address;
            location.formatted_addresses =
              info.formatted_addresses.standard_address;
            resolve(location);
          },
        });
      },
      fail(err) {
        reject(err);
      },
    });
  });
}

export function md5(message) {
  return CryptoJS.MD5(message).toString();
}

export function convertDistance(distance) {
  if (distance) {
    if (distance < 1000) {
      return distance.toFixed(2) + "m"; // 如果小于1000米，直接返回米
    } else {
      return (distance / 1000).toFixed(2) + "km"; // 如果大于或等于1000米，转换为千米并保留两位小数
    }
  } else {
    return "未知距离";
  }
}

export function vaildatorHeight(value) {
  let regex = /^([1-9]\d{0,2})$/;
  return regex.test(value);
}

export function heightFormatter(value) {
  // 获取当前输入值
  var inputValue = value;
  // 使用正则表达式替换掉非数字字符
  var numericValue = inputValue.replace(/\D/g, "");
  // 如果长度大于三位，则截取前三位
  if (numericValue.length > 3) {
    numericValue = numericValue.slice(0, 3);
  }
  // 如果数字小于1（即没有输入或只有0），则清空
  if (numericValue < 1) {
    numericValue = "";
  }
  return numericValue;
}

/**
 * @param {Object} params生成路由参数
 */
export function generateUrlOptions(params) {
  return encodeURIComponent(JSON.stringify(params));
}

/**
 * 解析 json
 */
export function parseJson(json, defaultValue = {}) {
  try {
    defaultValue = JSON.parse(json);
  } catch (e) {}
  return defaultValue;
}

/** 在组件内部调用的 时候使用 call(this) 进行调用
 * @param {Object} value
 * @param {Object} key
 */
export function limitAreaInput(value, formName, key) {
  value = value.replace(/[^\d.]/g, ""); //清除“数字”和“.”以外的字符
  value = value.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
  value = value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
  value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3"); //只能输入两个小数
  this.$nextTick(() => {
    this.$set(this[formName], key, value);
  });
  if (value.indexOf(".") < 0 && value != "") {
    //以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
    value = parseFloat(value);
    this.$nextTick(() => {
      this.$set(this[formName], key, value);
    });
  }
  if (value || value == "0" || value == "0.0" || value == "0.00") {
    return;
  }
}

/**
 * @param {Object} milliseconds格式化毫秒
 */
export function formatMilliseconds(milliseconds) {
  // 将毫秒转换为秒
  let seconds = Math.floor((milliseconds / 1000) % 60);
  // 将剩余的毫秒转换为分钟
  let minutes = Math.floor((milliseconds / (1000 * 60)) % 60);
  // 将剩余的分钟转换为小时
  let hours = Math.floor(milliseconds / (1000 * 60 * 60));

  // 确保每个部分至少有两个数字（如果需要的话，前面补0）
  hours = hours.toString().padStart(2, "0");
  minutes = minutes.toString().padStart(2, "0");
  seconds = seconds.toString().padStart(2, "0");

  // 拼接成 HH:mm:ss 格式
  return `${hours}:${minutes}:${seconds}`;
}

export function formatBytes(bytes, decimals = 2) {
  if (bytes === 0) return "0 Bytes";

  const k = 1024;
  const dm = decimals < 0 ? 0 : decimals;
  const sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];

  const i = Math.floor(Math.log(bytes) / Math.log(k));

  return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + " " + sizes[i];
}

/**
 * @param {Object} top设置 scrollViewTop 的值
 */
export function setScrollViewTop(top) {
  uni.setStorageSync("scrollViewTop", top);
}

/**
 * 获取 scrollViewTop 的值
 */
export function getScrollViewTop() {
  return uni.getStorageSync("scrollViewTop");
}

/**
 * @param {Object} 页面跳转
 */
export function navTo(data) {
  let {
    url,
    type,
    params = {}
  } = data;

  if (params) {
    // 如果 url 里面包含 ?
    if (~url.indexOf('?')) {
      url = url + "&params=" + encodeURIComponent(JSON.stringify(params))
    } else {
      url = url + "?params=" + encodeURIComponent(JSON.stringify(params))
    }
  }

  if (type == "tabBar") {
    uni.switchTab({
      url,
    });
  } else {
    uni.navigateTo({
      url,
    });
  }
}

// 身份证校验
export const idCardRule = (required = true) => {
  return [{
      required: required,
      errorMessage: "请填写身份证号！",
    },
    {
      validateFunction: (rule, value, data, callback) => {
        if (!checkIDCard(value)) {
          callback("请输入正确的证件号码!");
        }
        return true;
      },
    },
  ];
};

// 电话校验规则
export const phoneRule = (required = true) => {
  return [{
      required: required,
      errorMessage: "请填写联系电话！",
    },
    {
      validateFunction: (rule, value, data, callback) => {
        if (!regPhone(value)) {
          callback("请输入正确的联系电话!");
        }
        return true;
      },
    },
  ];
};

// 必填验证
export const requireInputRule = (message) => {
  return [{
      required: true,
      errorMessage: message,
    },
    {
      validateFunction: (rule, value, data, callback) => {
        if (!uniTrim(value)) {
          callback(message);
        }
        return true;
      },
    },
  ];
};

/**
 * 获取当天最后的时间 23:59:999 毫秒
 */
export function getLastTimeOfTheDay() {
  return moment().hour(23).minute(59).second(59).millisecond(999).valueOf();
}

export const customSubmitStyleHalf = {
  width: "324rpx",
  height: "88rpx",
  "border-radius": "44rpx 44rpx 44rpx 44rpx",
  background: "#2488f5",
  color: "#fff",
  padding: 0,
  margin: 0,
};

export function setDefaultProvinceCode(params, success) {
  if (!params.idCard) {
    return
  }
  getProvincecode(params)
    .then((res) => {
      if (res.code == 200) {
        const areaList = res.result.sort((a, b) => a.level - b.level);
        if (areaList.length) {
          this.areaList = areaList
          let address = areaList.map(item => item.departName).join('')
          let code = areaList[areaList.length - 1].nationCode
          this.defaultCityCode = code
          success({
            address,
            code
          })
        }
      }
    })
}


export function getRequestBaseUrl() {
  const cityInfo = uni.getStorageSync('cityInfo')
  // return 'http://192.168.1.161:8080/law-boot'
  return cityInfo.url
}

export function getRegionKey() {
  const cityInfo = uni.getStorageSync('cityInfo')
  let envKey = cityInfo.name ? cityInfo.name : ''
  return envKey
}


export function previewImage(urls) {
  const imgPrefix = uni.getStorageSync('imgPrefix')
  urls = urls.map((url) => {
    let needPrefix = true
    if (url.startsWith('http://') || url.startsWith('https://')) {
      needPrefix = false
    }
    return needPrefix ? imgPrefix + url : url
  })
  if (urls) {
    return uni.previewImage({
      urls: urls,
      success: (res) => {},
    });
  }
  return;
}

export const customSubmitStyleFull = {
  width: "680rpx",
  height: "88rpx",
  "border-radius": "44rpx 44rpx 44rpx 44rpx",
  background: "#2488f5",
  color: "#fff",
  padding: 0,
  margin: 0,
}

export const customSubmitStylePrev = {
  width: "680rpx",
  height: "88rpx",
  "border-radius": "44rpx 44rpx 44rpx 44rpx",
  border: "2rpx solid #2488F5",
  color: "#2488F5",
  padding: 0,
  margin: 0,
  'margin-right': '27rpx'
}

export const computedDistance = (lat1, lng1, lat2, lng2) => {
  lat1 = lat1 || 0;
  lng1 = lng1 || 0;
  lat2 = lat2 || 0;
  lng2 = lng2 || 0;
  var rad1 = lat1 * Math.PI / 180.0;
  var rad2 = lat2 * Math.PI / 180.0;
  var a = rad1 - rad2;
  var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
  var r = 6378137;
  var distance = r * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(rad2) * Math
    .pow(Math.sin(b / 2), 2)));

  return distance;
}

/**
 * @param {Object} n获取 n 天之后的日期
 */
export function getDateAfterNDays(n) {
  const currentDate = new Date();
  currentDate.setDate(currentDate.getDate() + n);
  return currentDate;
}

/**
 * 获取下一天的开始日期
 */
export function getNextDayStartDate() {
  const currentDate = new Date();
  const nextDay = new Date(currentDate);

  // 将日期设置为下一天
  nextDay.setDate(currentDate.getDate() + 1);

  // 将时间部分设置为00:00:00
  nextDay.setHours(0);
  nextDay.setMinutes(0);
  nextDay.setSeconds(0);
  nextDay.setMilliseconds(0);

  return nextDay;
}


export const halfColorButton = {
  height: '96rpx',
  background: '#DBECFF',
  'border-radius': '48rpx 48rpx 48rpx 48rpx',
  'font-weight': 500,
  'font-size': '36rpx',
  color: '#FFFFFF',
  border: '1rpx solid #ACCBEC'
}

export const ColorButton = {
  height: '96rpx',
  background: '#2488F5',
  'border-radius': '48rpx 48rpx 48rpx 48rpx',
  'font-weight': 500,
  'font-size': '36rpx',
  color: '#FFFFFF',
  border: '1rpx solid #ACCBEC'
}

export const logoutButton = {
  height: '96rpx',
  background: '#FFE4E4',
  'border-radius': '48rpx 48rpx 48rpx 48rpx',
  'font-weight': 500,
  'font-size': '36rpx',
  color: '#F22020',
  border: '1rpx solid #FFCECE'
}

export const cancelHalfButton = {
  width: '320rpx',
  height: '88rpx',
  background: '#EBEBEB',
  'border-radius': '44rpx 44rpx 44rpx 44rpx',
  color: '#1A1A1A'
}

export const submitHalfButton = {
  width: '320rpx',
  height: '88rpx',
  background: '#2488F5',
  'border-radius': '44rpx 44rpx 44rpx 44rpx',
  border: '1rpx solid #ACCBEC',
  color: '#F9F9F9'
}

// 获取某天最开始一刻
export function getZeroTimeOfDayAlternative(time) {
  const value = moment(time).valueOf()
  const currentDate = new Date(value);
  const year = currentDate.getFullYear();
  const month = currentDate.getMonth();
  const day = currentDate.getDate();
  const zeroTime = new Date(year, month, day, 0, 0, 0, 0); // 构造代表当天0点的Date对象
  const zeroTimeStamp = zeroTime.getTime();
  return zeroTimeStamp
}

// 获取某天最后一刻
export function getEndOfDayTimeAlternative(time) {
  const value = moment(time).valueOf()
  const currentDate = new Date(value);
  currentDate.setHours(23);
  currentDate.setMinutes(59);
  currentDate.setSeconds(59);
  currentDate.setMilliseconds(999);
  const endOfDayTimeStamp = currentDate.getTime();
  return endOfDayTimeStamp
}



//范围算法
export function ConvexHull(lines) {
  //排序去重
  for (let i = 0; i < lines.length; i++) {
    for (let j = 0; j < lines.length - i - 1; j++) {
      if (lines[j].x > lines[j + 1].x) {
        let tamp = lines[j]
        lines[j] = lines[j + 1]
        lines[j + 1] = tamp
      }
      if (lines[j].x == lines[j + 1].x && lines[j].y == lines[j + 1].y) {
        lines.splice(j + 1, 1)
        j--
      }
    }
  }
  let result = []
  let index = 1
  result.push(lines[0])
  while (true) {
    let point = findNext(lines, result[index - 2], result[index - 1])
    if (point == null) break
    result.push(point)
    if (point.x == lines[0].x && point.y == lines[0].y) {
      break
    }
    if (index > lines.length + 2) {
      break
    }
    index++
  }
  return result
}

function findNext(lines, start, node) {
  for (let i = 0; i < lines.length; i++) {
    if (start != null && start.x == lines[i].x && start.y == lines[i].y) {
      continue
    }
    if (node != null && node.x == lines[i].x && node.y == lines[i].y) {
      continue
    }
    let search = true
    let target = -9999
    for (let j = 0; j < lines.length; j++) {
      if (i == j) continue
      if (node != null && node.x == lines[j].x && node.y == lines[j].y) {
        continue
      }
      let left =
        sub(node.x, lines[j].x) * sub(lines[i].y, lines[j].y) - sub(node.y, lines[j].y) * sub(lines[i].x, lines[j]
          .x) >
        0 ?
        true :
        false
      if (target == -9999) {
        target = left
      }
      if (left != target) {
        search = false
        break
      }
    }
    if (search == true) {
      return lines[i]
    }
  }
}

function sub(a, b) {
  var c, d, e
  try {
    c = a.toString().split('.')[1].length
  } catch (f) {
    c = 0
  }
  try {
    d = b.toString().split('.')[1].length
  } catch (f) {
    d = 0
  }
  return (e = Math.pow(10, Math.max(c, d))), (mul(a, e) - mul(b, e)) / e
}

function mul(a, b) {
  var c = 0,
    d = a.toString(),
    e = b.toString()
  try {
    c += d.split('.')[1].length
  } catch (f) {}
  try {
    c += e.split('.')[1].length
  } catch (f) {}
  return (Number(d.replace('.', '')) * Number(e.replace('.', ''))) / Math.pow(10, c)
}

/**
 * @param {Object} time1 开始时间
 * @param {Object} time2 结束时间
 */
export function compareTime(time1, time2) {
  const date1 = new Date('1970-01-01T' + time1);
  const date2 = new Date('1970-01-01T' + time2);
  if (date1.getTime() < date2.getTime()) {
    return -1;
  } else if (date1.getTime() > date2.getTime()) {
    return 1;
  } else {
    return 0;
  }
}

export function hasToken() {
  let token = wx.getStorageSync("X-MINI-TOKEN");
  return !!token
}

export function parseIDCard(idCard) {
  // 校验身份证号码长度
  if (idCard.length !== 15 && idCard.length !== 18) {
    throw new Error("身份证号码长度不正确");
  }

  let birthDate, gender;

  // 处理18位身份证号码
  if (idCard.length === 18) {
    // 提取出生日期
    birthDate = `${idCard.substring(6, 10)}-${idCard.substring(10, 12)}-${idCard.substring(12, 14)}`;
    // 提取性别（第17位）
    gender = parseInt(idCard.charAt(16)) % 2 === 1 ? "男" : "女";
  }
  // 处理15位身份证号码
  else if (idCard.length === 15) {
    // 提取出生日期（补全年份为19XX）
    birthDate = `19${idCard.substring(6, 8)}-${idCard.substring(8, 10)}-${idCard.substring(10, 12)}`;
    // 提取性别（第15位）
    gender = parseInt(idCard.charAt(14)) % 2 === 1 ? "男" : "女";
  }

  return {
    birthDate,
    gender,
  };
}

export const halfCancelButton = {
  width: '320rpx',
  height: '88rpx',
  background: '#E1E1E1',
  'border-radius': '44rpx 44rpx 44rpx 44rpx',
  color: '#333333'
}

export const halfSaveButton = {
  width: '320rpx',
  height: '88rpx',
  background: '#2488F5',
  'border-radius': '44rpx 44rpx 44rpx 44rpx',
  border: '1rpx solid #ACCBEC',
  color: '#F9F9F9'
}

export const fullEditButton = {
  width: '680rpx',
  height: '88rpx',
  background: '#DFEFFF',
  'border-radius': '44rpx 44rpx 44rpx 44rpx',
  color: '#2488F5'
}

// 告警类型
export const alarmType = {
  1: 'SOS报警',
  4: '电子围栏报警',
  8: '心率异常'
}

export function daysBetween(date1, date2) {
  return moment(date2).diff(moment(date1), 'days');
}

export const problemTypeEnum = {
  1: '功能异常',
  2: '产品改进'
}

export const problemStatusEnum = {
  0: '已收到',
  1: '跟进中',
  2: '已处理',
}

export function encryptIDCard(idCard) {
  if (!idCard) {
    return '暂无'
  }
  return idCard.slice(0, 6) + '********' + idCard.slice(14);
}